/**
 * 
 */
package com.mycompany.inventory.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import org.zkoss.zul.Image;

import sun.awt.image.BufferedImageGraphicsConfig;


/**
 * @author loitran
 *
 */
public class ImageUtil {
		public BufferedImage currentImage;
		public Image pgcImage; // Zk image component

	    /*
	     * LOAD image from any byte array. In this case I use an EJB from database with a blob field.
	    */
	    public void loadImage( byte[] object ) throws IOException
	    {
	        ByteArrayInputStream is = new ByteArrayInputStream( object );
	        currentImage = ImageIO.read( is );
	    }

	    public BufferedImage showImage() throws IOException
	    {
	        int w = currentImage.getWidth();
	        int h = currentImage.getHeight();
	        if(w > 0 && h > 0){
	        	BufferedImage bufferedImage = resizeTrick( currentImage, w, h );
	           return bufferedImage;
	        }else{
	        	return currentImage;
	        }
	    }

	    private static BufferedImage resizeTrick( BufferedImage image, int width, int height )
	    {
	        image = createCompatibleImage( image );
	        //image = blurImage( image );
	        image = resize( image, width, height );
	        return image;
	    }

	    private static BufferedImage createCompatibleImage( BufferedImage image )
	    {
	        GraphicsConfiguration gc = BufferedImageGraphicsConfig.getConfig( image );
	        int w = image.getWidth();
	        int h = image.getHeight();
	        BufferedImage result = gc.createCompatibleImage( w, h, Transparency.TRANSLUCENT );
	        Graphics2D g2 = result.createGraphics();
	        g2.drawRenderedImage( image, null );
	        g2.dispose();
	        return result;
	    }

	    private static BufferedImage resize( BufferedImage image, int width, int height )
	    {
	        int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
	        BufferedImage resizedImage = new BufferedImage( width, height, type );
	        Graphics2D g = resizedImage.createGraphics();
	        g.setComposite( AlphaComposite.Src );

	        g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );

	        g.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );

	        g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

	        g.drawImage( image, 0, 0, width, height, null );
	        g.dispose();
	        return resizedImage;
	    }
}
